﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bamuca.Codigo.DTO;
using MySql.Data.MySqlClient;
using System.Data;
using System.Text;

namespace Bamuca.Codigo.DAO
{
    public class RotinaDao: ConexaoDao
    {

        MySqlConnection conn = ConexaoDao.SqlConectar();
        MySqlCommand cmd = new MySqlCommand();
   
        public void Inserir(RotinaDto _rotina)
        {            
            try
            {
                cmd.Connection = conn;
                cmd.CommandText = "insert into rotinas (nome) values ('" + _rotina.Nome + "')";
                cmd.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }            
        }

        public void Alterar(RotinaDto _rotina)
        {
            try
            {
                cmd.Connection = conn;
                cmd.CommandText = "update rotinas SET nome = '" + _rotina.Nome + "' " +
                "WHERE idrotina = " + _rotina.IdRotina;
                cmd.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                throw ex;
            }

        }

        public void Excluir(RotinaDto _rotina)
        {
            try
            {
                cmd.Connection = conn;
                cmd.CommandText = "delete rotinas WHERE idrotina = " + _rotina.IdRotina;
                cmd.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                throw ex;
            }

        }

        public DataTable ConsultarTodasPorParametro(RotinaDto _rotinaDto)
        {
            MySqlDataAdapter dtAdap;
            DataTable dtTable = new DataTable();

            string _strSql = "SELECT * FROM rotinas WHERE 1=1 ";
            if (_rotinaDto.IdRotina > 0)
            {
                _strSql = _strSql + "AND idrotina = " + _rotinaDto.IdRotina + " ";
            }
            if (_rotinaDto.Nome  != string.Empty )
            {
                _strSql = _strSql + "AND nome LIKE '%" + _rotinaDto.Nome + "'% ";
            }

            try
            {
                dtAdap = new MySqlDataAdapter(_strSql, conn);
                dtAdap.Fill(dtTable);
            }
            catch (MySqlException ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }

            return dtTable;
        }
    }
}